package com.archstoday.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.EngineesDetailsEntity;
import com.archstoday.entity.NewsDetailsEntity;
import com.archstoday.entity.ShareEntity;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.PdfURLUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.utils.WechatUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.shuyu.action.web.ActionSelectListener;
import com.shuyu.action.web.CustomActionWebView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 要闻详情页面
 */
public class NewDetailsActivity extends AsBaseActivity {

    private TextView mTitleTv;
    private TextView mDetailsTitleTv, mFromeTv, mDesTv, mReadBtn,
            mLikeBtn, mCommentBtn;
    private CustomActionWebView mWebView;
    private LinearLayout mOffLineLayout;
    private ProgressBar mProgress;

    private int articleID;
    private boolean isNews;
    private String mChannel;

    private NewsDetailsEntity mNewsEntity;
    private EngineesDetailsEntity mEgEntity;
    private String mAction;

    List<String> list;

    private MyTimeTask mTimeTask;
    private Timer timer;
    private int recLen;

    class MyTimeTask extends TimerTask {
        @Override
        public void run() {
            Message message = new Message();
            handler.sendMessage(message);
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(recLen == 0){
                mLikeBtn.setEnabled(true);
            }
            recLen--;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimeTask != null) {
            mTimeTask.cancel();
        }
    }

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_new_details);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mDetailsTitleTv = (TextView) findViewById(R.id.details_title_tv);
        mFromeTv = (TextView) findViewById(R.id.details_from_tv);
        mDesTv = (TextView) findViewById(R.id.details_des_tv);
        mWebView = (CustomActionWebView) findViewById(R.id.details_content_view);
        mReadBtn = (TextView) findViewById(R.id.details_btn);
        mLikeBtn = (TextView) findViewById(R.id.details_like_btn);
        mCommentBtn = (TextView) findViewById(R.id.details_discussion_btn);
        mOffLineLayout = (LinearLayout) findViewById(R.id.offline_layout);
        mProgress = (ProgressBar) findViewById(R.id.web_progress);
    }

    @Override
    protected void initData(Bundle bundle) {
        list = new ArrayList<>();
        list.add("拷贝");
        list.add("分享文字");

        isNews = getIntent().getBooleanExtra("isNews", false);
        initSetting();
        if (isNews) {
            mTitleTv.setText("要闻详情");
            mReadBtn.setVisibility(View.GONE);
            articleID = getIntent().getIntExtra("id", 0);
            upNewsData();
        } else {
            mTitleTv.setText(StringUtil.isEmpty(getIntent().getStringExtra("title"))
                    ? "标准规范公告" : getIntent().getStringExtra("title"));
            mLikeBtn.setVisibility(View.GONE);
            mCommentBtn.setVisibility(View.GONE);
            articleID = Integer.valueOf(getIntent().getStringExtra("id"));
            mReadBtn.setVisibility(View.GONE);
            upEgData();
        }
    }

    private void initSetting() {
        WebSettings ws = mWebView.getSettings();
        ws.setBuiltInZoomControls(false);
        ws.setSupportZoom(false);
        ws.setJavaScriptEnabled(true);
        ws.setAllowFileAccess(true);
        ws.setSupportMultipleWindows(true);
        ws.setJavaScriptCanOpenWindowsAutomatically(true);
        ws.setLoadsImagesAutomatically(true);
        ws.setDomStorageEnabled(true);
        ws.setDisplayZoomControls(false);
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        ws.setUseWideViewPort(true);
        ws.setLoadWithOverviewMode(true);
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mProgress.setProgress(newProgress);
                if (newProgress == 100) {
//                    mProgress.setVisibility(View.GONE);
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        mWebView.setWebViewClient(new CustomWebViewClient());

        //设置item
        mWebView.setActionList(list);

        //链接js注入接口，使能选中返回数据
        mWebView.linkJSInterface();

        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        //使用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);

        //增加点击回调
        mWebView.setActionSelectListener(new ActionSelectListener() {

            @Override
            public void onClick(String title, String selectText) {
                Log.e("onClick", "onClick--");

                if (title.equalsIgnoreCase("分享文字")) {
                    Intent intent = new Intent();
                    intent.putExtra("id", articleID);
                    intent.putExtra("content", selectText);
                    intent.putExtra("type", isNews ? "news" : "ep");
                    intent.putExtra("categoryId1",
                            isNews ? mNewsEntity.getData().getCategoryId1() : 0);//mEgEntity.getData().getCategoryId1());

                    intent.setClass(mContext, TextShareActivity.class);
                    startActivity(intent);
                }

                if (title.equalsIgnoreCase("拷贝")) {
                    ToolUtils.copyUrl(mContext, selectText);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.dismissAction();
        }
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);
        setOnClickListener(R.id.details_btn);
        setOnClickListener(R.id.details_share_btn);
        setOnClickListener(R.id.details_like_btn);
        setOnClickListener(R.id.details_discussion_btn);
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;
            case R.id.details_btn:
                if (isNews) {

                } else {
//                    if (!ToolUtils.isWifiConnected(mContext)) {
//                        showToast("请在wifi环境下查看");
//                        return;
//                    }

                    getEvent(mApp.E_READ, mApp.PAGE_TYPE_READ);
                    if (!StringUtil.isEmpty(mEgEntity.getData().getPdfAttachment())) {
                        if (ToolUtils.isPermission(mContext)) {
                            String pdfAddress = mEgEntity.getData().getPdfAttachment();
                            if (pdfAddress.indexOf(",") > 0) {
                                if (pdfAddress.indexOf("[") == 0) {
                                    pdfAddress = pdfAddress.substring(pdfAddress.indexOf("[") + 1, pdfAddress.indexOf(","));
                                } else {
                                    pdfAddress = pdfAddress.substring(0, pdfAddress.indexOf(","));
                                }
                            } else {
                                if (pdfAddress.indexOf("[") == 0) {
                                    pdfAddress = pdfAddress.substring(pdfAddress.indexOf("[") + 1, pdfAddress.indexOf("]"));
                                }
                            }

                            Intent intent = new Intent(mContext, DownloadPdfActivity.class);
                            intent.putExtra("url", PdfURLUtils.getInstance().getPdf_url()
                                    + pdfAddress);
                            startActivity(intent);
                        } else {
                            ToolUtils.getAppDetailSettingIntent(mContext);
                        }
                    } else if (!StringUtil.isEmpty(mEgEntity.getData().getSourcedetailLink())) {
                        Intent intent = new Intent(mContext, WebActivity.class);
                        intent.putExtra("url", mEgEntity.getData().getSourcedetailLink());
                        startActivity(intent);
                    }
                }
                break;
            case R.id.details_share_btn:
                setDialog();
                break;
            case R.id.share_wx_btn:
                Map<String, String> info = new HashMap<>();
                if (isNews) {
                    info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                    info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                } else {
                    info.put("articleId", String.valueOf(mEgEntity.getData().getArticleId()));
//                    info.put("categoryId1", String.valueOf(mEgEntity.getData().getCategoryId1()));
                }
                info.put("channel", "wechat");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));

                mChannel = "wechat";
                share();
                break;
            case R.id.share_group_btn:
                info = new HashMap<>();
                if (isNews) {
                    info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                    info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                } else {
                    info.put("articleId", String.valueOf(mEgEntity.getData().getArticleId()));
//                    info.put("categoryId1", String.valueOf(mEgEntity.getData().getCategoryId1()));
                }
                info.put("channel", "friends");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));


                mChannel = "friends";
                share();
                break;
            case R.id.share_link_btn:
                info = new HashMap<>();
                if (isNews) {
                    info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                    info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                } else {
                    info.put("articleId", String.valueOf(mEgEntity.getData().getArticleId()));
//                    info.put("categoryId1", String.valueOf(mEgEntity.getData().getCategoryId1()));
                }
                info.put("channel", "link");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));


                mChannel = "msg";
                share();
                break;
            case R.id.details_like_btn:
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    appFinish();
                } else {
                    info = new HashMap<>();
                    if (isNews) {
                        info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                        info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                    } else {
                        info.put("articleId", String.valueOf(mEgEntity.getData().getArticleId()));
//                    info.put("categoryId1", String.valueOf(mEgEntity.getData().getCategoryId1()));
                    }
                    getEvent(BaseApp.E_FAV, BaseApp.PAGE_TYPE_FAV,
                            ToolUtils.mapToJson(info));

                    if (mLikeBtn.isSelected()) {
                        mAction = "del";
                        like();
                    } else {
                        mAction = "add";
                        like();
                    }

                    mLikeBtn.setEnabled(false);
                    timer = new Timer();
                    mTimeTask = new MyTimeTask();
                    recLen = 1;
                    timer.schedule(mTimeTask, 1000, 1000);
                }
                break;
            case R.id.details_discussion_btn:
                info = new HashMap<>();
                if (isNews) {
                    info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                    info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                } else {
                    info.put("articleId", String.valueOf(mEgEntity.getData().getArticleId()));
//                    info.put("categoryId1", String.valueOf(mEgEntity.getData().getCategoryId1()));
                }
                getEvent(BaseApp.E_COMMENT, BaseApp.PAGE_TYPE_COMMENT,
                        ToolUtils.mapToJson(info));

                Intent specialIntent = new Intent();
//                specialIntent.putExtra("data", mSchemeEntity);
                specialIntent.putExtra("articleId", mNewsEntity.getData().getArticleId());
                specialIntent.putExtra("categoryId1", mNewsEntity.getData().getCategoryId1());
                specialIntent.setClass(mContext, SpecialCommentActivity.class);
                startActivity(specialIntent);
                break;
        }
    }

    private void like() {
        initParameter();
        mParams.put("articleId", String.valueOf(articleID));
        mParams.put("categoryId1", mNewsEntity.getData().getCategoryId1());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("action", mAction);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.EDIT_LIKE),
                AsRes.EDIT_LIKE, mParams, BaseEntity.class);
    }

    private void upNewsData() {
        initParameter();
        mParams.put("id", articleID);
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("toke", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_NEWS_DETAILS),
                AsRes.GET_NEWS_DETAILS, mParams, NewsDetailsEntity.class);
    }

    private void upEgData() {
        initParameter();
        mParams.put("id", articleID);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_ENGINEER_DETAILS),
                AsRes.GET_ENGINEER_DETAILS, mParams, EngineesDetailsEntity.class);
    }

    private void share() {
        initParameter();
        mParams.put("articleID", articleID);
        mParams.put("type", isNews ? "news" : "ep");
        mParams.put("channel", mChannel);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.SHARE),
                AsRes.SHARE, mParams, ShareEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.GET_NEWS_DETAILS) {
            mNewsEntity = (NewsDetailsEntity) parse;
            if (ToolUtils.isSuccess(mNewsEntity.getStatus())) {
                mDetailsTitleTv.setText(mNewsEntity.getData().getTitle());
                mFromeTv.setText(mNewsEntity.getData().getUserName());
                mDesTv.setText(mNewsEntity.getData().getCreateTime());
                mLikeBtn.setText(String.valueOf(mNewsEntity.getData().getUpvote()));
                mLikeBtn.setSelected(mNewsEntity.getData().getIslike() == 1 ? true : false);
                mCommentBtn.setText(String.valueOf(mNewsEntity.getData().getComments()));
//                if (mNewsEntity.getData().getIslike() == 0) {
//                    mLikeBtn.setTextColor(mContext.getResources().getColor(R.color.black));
//                } else {
//                    mLikeBtn.setTextColor(mContext.getResources().getColor(R.color.scheme_yellow));
//                }

                if (StringUtil.equest("3", mNewsEntity.getData().getType())) {
                    mWebView.loadUrl(mNewsEntity.getData().getSourceDetailLink());
                } else {
                    mWebView.loadDataWithBaseURL(null,
                            mNewsEntity.getData().getContent(), "text/html", "utf-8", null);
                }
            }  else if (mNewsEntity.getStatus() == 444) {
                mOffLineLayout.setVisibility(View.VISIBLE);
            } else {
                showToast(mNewsEntity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.GET_ENGINEER_DETAILS) {
            mEgEntity = (EngineesDetailsEntity) parse;
            if (ToolUtils.isSuccess(mEgEntity.getStatus())) {
                mDetailsTitleTv.setText(mEgEntity.getData().getTitle());
                mFromeTv.setText(mEgEntity.getData().getReleaseOrg());
                if (!StringUtil.isEmpty(mEgEntity.getData().getIndexNo())) {
                    mDesTv.setText("编号:" + mEgEntity.getData().getIndexNo());
                }
                mReadBtn.setVisibility(StringUtil.isEmpty(mEgEntity.getData().getPdfAttachment())
                        && StringUtil.isEmpty(mEgEntity.getData().getSourcedetailLink())
                        ? View.GONE : View.VISIBLE);
                mWebView.loadDataWithBaseURL(null,
                        mEgEntity.getData().getContent(), "text/html", "utf-8", null);
            } else {
                showToast(mEgEntity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.SHARE) {
            ShareEntity entity = (ShareEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                getEvent(mApp.E_SHARE, mApp.PAGE_TYPE_SHARE);
                switch (mChannel) {
                    case "wechat":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                false);
                        break;
                    case "friends":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                true);
                        break;
                    case "msg":
                        ToolUtils.copyUrl(mContext, entity.getData().getUrl());
                        break;
                }
                dismissShare();
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.EDIT_LIKE) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                switch (mAction) {
                    case "add":
                        mLikeBtn.setText(String.valueOf(mNewsEntity.getData().getUpvote() + 1));
                        mNewsEntity.getData().setUpvote(mNewsEntity.getData().getUpvote() + 1);
                        break;
                    case "del":
                        mLikeBtn.setText(String.valueOf(mNewsEntity.getData().getUpvote() - 1));
                        mNewsEntity.getData().setUpvote(mNewsEntity.getData().getUpvote() - 1);
                        break;
                }
                mLikeBtn.setSelected(!mLikeBtn.isSelected());
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    private class CustomWebViewClient extends WebViewClient {

        private boolean mLastLoadFailed = false;

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            if (!mLastLoadFailed) {
                CustomActionWebView customActionWebView = (CustomActionWebView) webView;
                customActionWebView.linkJSInterface();
            }
        }

        @Override
        public void onPageStarted(WebView webView, String url, Bitmap favicon) {
            super.onPageStarted(webView, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLastLoadFailed = true;
        }
    }
}